<template>
  <a-card class="task-tabs-card">
    <template #title>
      <div v-if="TaskStatusEnum.draft === taskInfo.taskStatus && !disabled" class="flex items-center justify-between">
        <div style="line-height: 32px">
          是否需要文件清单：
          <a-radio-group v-model:value="isNeedFile" @change="isNeedApprovalChange">
            <a-radio :value="true">需要</a-radio>
            <a-radio :value="false">不需要</a-radio>
          </a-radio-group>
        </div>
        <div>
          <a-space>
            <a-button v-if="isNeedFile && !tableData.length" type="primary" @click="refSelectFileTem.show()">
              选择文件清单
            </a-button>
            <AddBtn
              v-if="isNeedFile && tableData.length"
              type="primary"
              @click="refAddFile.show(tableData.length + 1, 'add')"
              >新增文件清单</AddBtn
            >
          </a-space>
        </div>
      </div>
    </template>
    <TnNewTable
      v-if="isNeedFile"
      :tn-table-props="tnTableProps"
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'fileName'">
          {{ record.fileName }} <br />
          <span class="fileDesc" :title="record.fileDesc">
            {{ record.fileDesc }}
          </span>
        </template>
        <template v-if="column.dataIndex === 'requireFile'">
          {{ record.requireFile === 1 ? '是' : '否' }}
        </template>
        <template v-if="column.dataIndex === 'requireVersion'">
          {{ record.requireVersion === 1 ? '是' : '否' }}
        </template>
        <template v-if="column.dataIndex === 'complementFile'">
          {{ record.complementFile === 1 ? '是' : '否' }}
        </template>
        <template v-if="column.dataIndex === 'fileFormat'">
          {{ record.fileFormat && record.fileFormat.length ? record.fileFormat.join('、') : '' }}
        </template>
        <template v-if="column.dataIndex === 'signFlag'">
          {{ record.signFlag ? '是' : '否' }}
          <a-button v-if="record.signFlag" type="link" primary @click="getSignSet(record)">查看</a-button>
        </template>

        <template v-if="column.dataIndex === 'templateFile'">
          <template v-if="record.templateFileList && record.templateFileList.length > 0">
            <template v-for="item in record.templateFileList">
              <FilePreview :file="item" :add-watermark-flag="false" operation-type="1058" />
              <!-- <a href="#">{{ item.tempFileName }}</a> <br /> -->
            </template>
          </template>
          <template v-else>无</template>
        </template>

        <template v-if="column.dataIndex === 'pathName'">
          {{ record.pathName || record.archiveFolderName }}
        </template>
        <template v-if="column.dataIndex === 'edit' && !disabled">
          <template v-if="TaskStatusEnum.draft === taskInfo.taskStatus">
            <a-button type="link" primary @click="refAddFile.show(record, 'edit')">编辑</a-button>
            <a-popconfirm
              title="是否确认删除?"
              ok-text="确认"
              cancel-text="取消"
              :get-popup-container="(triggerNode):any => triggerNode.parentNode"
              @cancel="() => {}"
              @confirm="delHandle(record.fileListItemId)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>

            <Icon
              v-if="index < tableData.length - 1"
              size="20"
              class="cursor-pointer align-middle"
              @click="changeOrder('down', index)"
              ><ArrowCircleDown20Regular color="#0177fd"></ArrowCircleDown20Regular
            ></Icon>
            <Icon v-if="index > 0" size="20" class="cursor-pointer align-middle" @click="changeOrder('up', index)"
              ><ArrowCircleUp28Regular color="#0177fd"></ArrowCircleUp28Regular
            ></Icon>
          </template>
        </template>
      </template>
    </TnNewTable>
    <IcpEmpty v-else />
  </a-card>
  <SelectFileTem
    ref="refSelectFileTem"
    :task-id="taskInfo.taskId"
    :submit-fn="taskInfo.selectFileListApi"
    :mutil-add-fn="taskInfo.selectWhiteApi"
    :filter-columns-code="props.filterColumnsCode && props.filterColumnsCode.includes('signFlag') ? 'signFlag' : ''"
    :hide-sign-setting="props.hideSignSetting"
    :tag="props.tag"
    @onReloadTable="reloadTable"
  />
  <AddFile
    ref="refAddFile"
    :task-id="taskInfo.taskId"
    :task-type="taskInfo.taskType"
    :is-need-select-folder="isNeedSelectFolderFlag"
    :speed-id="taskInfo.speedId"
    :update-fn="taskInfo.updateFileListApi"
    :source="source"
    :add-fn="taskInfo.addFileListApi"
    :hide-sign-setting="props.hideSignSetting"
    :tag="props.tag"
    :is-by-project-type="props.isByProjectType"
    :is-input-folder="props.isInputFolder"
    :no-data-msg="props.noDataMsg"
    :project-type="props.projectType"
    @onReloadTable="reloadTable"
  ></AddFile>
  <SignSetPage ref="refSignSetPage" />
</template>

<script lang="ts" setup>
import { computed, ref, Ref } from 'vue'
import SelectFileTem from './components/SelectFileTem.vue'
import AddFile from './components/AddFile.vue'
import SignSetPage from './components/SignSetPage.vue'
import { taskColumnsList } from './index'
import { ArrowCircleDown20Regular, ArrowCircleUp28Regular } from '@vicons/fluent'
import { TaskStatusEnum } from '@@/enums/taskEnum'
import { viewSignSet } from '@@/api/signFile'

const emits = defineEmits(['resetData'])
const props = defineProps<{
  taskInfo: any
  needFile: boolean | undefined | number
  disabled?: boolean
  isNeedSelectFolder: boolean
  filterColumnsCode?: String
  source?: string
  tag?: number | string
  hideSignSetting?: boolean
  fileKey?: number // 后端转为1 2 4 8 16 32来接收,现在只有药房业务配置使用该方式
  isByProjectType?: any
  projectType?: any
  noDataMsg?: string // 没有文件夹目录的时候,点选择的提示文案
  isInputFolder?: boolean // 是否手动输入文件归档目录
}>()
// const { taskInfo, needFile, filterColumnsCode, isNeedSelectFolder = true } = toRefs(props)
const isNeedSelectFolderFlag = computed(() => {
  if (props.isNeedSelectFolder === undefined || props.isNeedSelectFolder === null) {
    return true
  }
  return props.isNeedSelectFolder
})

const columns = taskColumnsList.filter((item: any) => {
  if (!props.filterColumnsCode) {
    return true
  } else if (props.filterColumnsCode.includes(item.dataIndex)) {
    return false
  }
  return true
})

const refSelectFileTem = ref<any>(null)
const refAddFile = ref()
const isNeedFile = ref(
  props.fileKey ? (Number(props.needFile) & props.fileKey) === props.fileKey : props.needFile ? true : false
)
const isNeedApprovalChange = () => {
  const taskId = props.taskInfo.mainId || 'taskId'
  const required = props.taskInfo.isPerNeedFile || 'required'
  let requiredVal
  if (props.fileKey) {
    if ((Number(props.needFile) & props.fileKey) === props.fileKey) {
      requiredVal = isNeedFile.value ? props.needFile : Number(props.needFile) - props.fileKey
    } else {
      requiredVal = isNeedFile.value ? Number(props.needFile) + props.fileKey : props.needFile
    }
  } else {
    requiredVal = isNeedFile.value
  }
  props.taskInfo
    .updateFileRequiredApi({
      [taskId]: props.taskInfo.taskId,
      [required]: requiredVal
    })
    .then(() => {
      emits('resetData', requiredVal)
    })
    .catch(() => {
      isNeedFile.value = props.fileKey
        ? (Number(props.needFile) & props.fileKey) === props.fileKey
        : props.needFile
        ? true
        : false
    })
}
const tableData: Ref<any[]> = ref([])
type ObjectType = {
  templateFile?: string
  templateFileList?: []
}
const reloadTable = () => {
  console.log(props.tag)
  props.taskInfo
    .getTaskFileListApi({ taskId: props.taskInfo.taskId, tag: props.tag })
    .then((res) => {
      tableData.value = res
      if (tableData.value.length) {
        tableData.value.forEach((element: ObjectType) => {
          if (element.templateFile && element.templateFile !== '[]') {
            element.templateFileList = JSON.parse(element.templateFile)
          } else {
            element.templateFileList = []
          }
        })
      }
      tnTableProps.value.tableData = tableData.value
    })
    .catch(() => {})
}
reloadTable()
const tnTableProps = ref({
  name: 'CommonTaskKanbanfileListTable',
  tableData: tableData.value,
  showNo: false,
  needPagination: false,
  needToolbar: false
})
const delHandle = (fileListItemId) => {
  props.taskInfo
    .delFileListApi({ fileListItemId })
    .then(() => {
      reloadTable()
    })
    .catch(() => {})
}
interface objFormat {
  fileListItemId?: string
  displayOrder?: number
}
const changeOrder = (type, index) => {
  const arr: any[] = []
  const obj: objFormat = {}
  const toObj: objFormat = {}
  if (type === 'up') {
    obj.fileListItemId = tableData.value[index].fileListItemId
    toObj.fileListItemId = tableData.value[index - 1].fileListItemId
    obj.displayOrder = tableData.value[index - 1].displayOrder
    toObj.displayOrder = tableData.value[index].displayOrder
  } else {
    obj.fileListItemId = tableData.value[index].fileListItemId
    toObj.fileListItemId = tableData.value[index + 1].fileListItemId
    obj.displayOrder = tableData.value[index + 1].displayOrder
    toObj.displayOrder = tableData.value[index].displayOrder
  }
  arr.push(obj)
  arr.push(toObj)
  props.taskInfo.displayOrderFileListApi(arr).then(() => {
    reloadTable()
  })
}
const refSignSetPage = ref()
const getSignSet = async (item) => {
  const res = await viewSignSet({
    taskId: item.taskId,
    sopFlag: props.taskInfo.sourceType === 'project' ? false : true
  })
  refSignSetPage.value.show(res, { ...item })
}
</script>

<style lang="less"></style>
